package com.itheima.controller;


import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.Result;
import com.itheima.entity.TeleCodeDTO;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 会员管理
 */
@Api(tags = "MemberController-会员管理")
@RestController
@RequestMapping("/member")
public class MemberController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MemberService memberService;
    //会员手机快速登录
    @ApiOperation(value = "会员手机快速登录",notes = "会员手机快速登录")
    @ApiImplicitParam(name = "teleCodeDTO",value = "手机验证码",required = true,dataType = "TeleCodeDTO")
    @PostMapping("/login")
    public Result login(HttpServletResponse response,@RequestBody TeleCodeDTO teleCodeDTO){
        String telephone = teleCodeDTO.getTelephone();
        String validateCode = teleCodeDTO.getValidateCode();

        //从redis中获取保存的验证码
        String codeInRedis = (String) redisTemplate.opsForValue().get(telephone + RedisConstant.SENDTYPE_LOGIN);

        //比对校验验证码
        if(codeInRedis == null || validateCode == null || !validateCode.equals(codeInRedis)){
            //校验不通过，返回
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

        Member member = memberService.findByTelephone(telephone);
        //校验通过，判断是否为会员，如果不是会员自动完成注册
        if(member == null){
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            memberService.add(member);
        }

        //将用户手机号保存到cookie，为了跟踪用户
        Cookie cookie = new Cookie("login_member_telephone",telephone);
        cookie.setPath("/");
        cookie.setMaxAge(60*60*24*30);
        response.addCookie(cookie);

        String memberJson = JSON.toJSON(member).toString();
        //将用户信息保存到redis（模拟session）
        redisTemplate.opsForValue().set(telephone, memberJson, 30, TimeUnit.MINUTES);
        return new Result(true,MessageConstant.LOGIN_SUCCESS);
    }
}
